package com.zigong.app.ui.activities;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.Pair;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.gridsum.tracker.GridsumWebDissector;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.zigong.app.R;
import com.zigong.app.application.Constances;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.beans.FVersionInfo;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.dialog.FontSizeDiaFragment;
import com.zigong.app.ui.dialog.ShowDiaFragment;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.ui.utils.cache.DataCleanManager;
import com.zigong.app.ui.utils.update.DownloadManager;
import com.zigong.app.utils.UserManager;
import com.zigong.app.utils.VersionUtil;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 设置
 */
public class MineSettingActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.mine_font_size_content)
    protected CustomFontTextView font_tv;
    @BindView(R.id.mine_cache_size)
    protected CustomFontTextView cache_tv;
    @BindView(R.id.mine_push_cb)
    protected CustomCheckBox push_cb;
    @BindView(R.id.tv_version)
    protected CustomFontTextView tv_version;
    @BindView(R.id.login_out)
    protected CustomFontTextView loginOut;

    private final int REQUEST_TO_LOGIN = 10;
    public static final String SHOW_TAG = "dia_show_fragment";
    public static final String FONT_TAG = "dia_font_size_fragment";
    private Dialog updateDialog = null;
    private boolean isUpdate = false;
    private DownloadManager manager = null;
    private FVersionInfo versionInfo;
    private FontSizeDiaFragment fontSizeDiaFragment;
    private ShowDiaFragment showDiaFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("设置");
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_mine_setting);
        ButterKnife.bind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        initBuildLay();
        getVersion();
        checkFontSize();
        initData();
        checkUser();
    }
    /**
     * 判断用户是否登录
     */
    private void checkUser() {
        if(null!=UserManager.getInstance().getUser()) {
            loginOut.setVisibility(View.VISIBLE);
        } else {
            loginOut.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.mine_font_size, R.id.mine_clean_cache, R.id.mine_account_save, R.id.mine_about, R.id.login_out,R.id.mine_rule})
    public void mineClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "设置"));
        pairs.add(new Pair<>("行为类型", "点击"));
        switch (view.getId()) {
            case R.id.mine_clean_cache:
                GridsumWebDissector.getInstance().trackEvent(this, "", "清理缓存", "", 200, pairs);
                showProgress("正在清理缓存...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        DataCleanManager.clearAllCache(MineSettingActivity.this);
                        MineSettingActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    toast(getString(R.string.mine_cache_success));
                                    String size = DataCleanManager.getTotalCacheSize(MineSettingActivity.this);
                                    cache_tv.setText(size);
                                    closeProgress();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }).start();

                break;
            case R.id.mine_account_save:
                GridsumWebDissector.getInstance().trackEvent(this, "", "账号与安全", "", 200, pairs);
                if(null!=UserManager.getInstance().getUser()) {
                    Intent intent = new Intent(this, UserInfoActivity.class);
                    startActivityForResult(intent, REQUEST_TO_LOGIN);
                } else {
                    toLogin();
                }
                break;
            case R.id.mine_about:
                GridsumWebDissector.getInstance().trackEvent(this, "", "关于", "", 200, pairs);
                Intent aboutIntent = new Intent(this, AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.mine_font_size:
                //设置字体大小
                GridsumWebDissector.getInstance().trackEvent(this, "", "字体大小", "", 200, pairs);
                showFontDialog();
                break;
            case R.id.login_out:
                //退出登陆
                GridsumWebDissector.getInstance().trackEvent(this, "", "退出登录", "", 200, pairs);
                showLoginOutDialog();
                break;
            case R.id.mine_rule:
                GridsumWebDissector.getInstance().trackEvent(this, "", "用户协议与隐私政策", "", 200, pairs);
                Intent intent = new Intent(this, MyRuleAndPolicyActivity.class);
                startActivity(intent);
                break;
        }
    }


    /**
     * 显示切换字体大小的弹出框
     */
    private synchronized void showFontDialog() {
//        if (fontSizeDiaFragment == null) {
        fontSizeDiaFragment = new FontSizeDiaFragment();
//        }
//        if (fontSizeDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName(), 50)) {
//            return;
//        }
        fontSizeDiaFragment.setCallBack(callBack);
        FragmentManager fm = this.getSupportFragmentManager();
        fontSizeDiaFragment.show(fm, FONT_TAG);
        fm.executePendingTransactions();
    }

    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            parseWhat(msg.what);
        }
    };

    /**
     * 切换字体后回调刷新UI
     *
     * @param what
     */
    private void parseWhat(int what) {
        if (what == Constances.BIG_FONT) {
            font_tv.setText("大");
        } else if (what == Constances.MID_FONT) {
            font_tv.setText("中");
        } else if (what == Constances.SMALL_FONT) {
            font_tv.setText("小");
        }else if (what == ShowDiaFragment.LOGINOUT_TAG) {
            SkipUtil.skipToAddUserOperate( this, getOwnerName(),   21, 0, "退出登录", "", "");
            UserManager.getInstance().setUser(this, null);
            UserManager.getInstance().delUserCache(this);
            checkUser();
            finish();
        }
    }

    /**
     * 初始化推送消息的开关状态
     */
    private void initBuildLay() {
        boolean isPush = (boolean) SharedPreferencesUtil.getParam(this, "PUSH_KEY", false);
        if (isPush) {
            push_cb.setChecked(true);
        } else {
            push_cb.setChecked(false);
        }
        push_cb.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "设置"));
        pairs.add(new Pair<>("行为类型", "点击"));
        if (isChecked) {
            GridsumWebDissector.getInstance().trackEvent(this, "", "接受推送", "", 200, pairs);
            JPushInterface.init(this.getApplicationContext());
            JPushInterface.resumePush(this);
            JPushInterface.setAlias(this, 0, "scgc2_0");
            SharedPreferencesUtil.setParam(this, "PUSH_KEY", true);
        } else {
            GridsumWebDissector.getInstance().trackEvent(this, "", "拒绝推送", "", 200, pairs);
            JPushInterface.stopPush(this);
            SharedPreferencesUtil.setParam(this, "PUSH_KEY", false);
        }
    }

    /**
     * 初始化显示当前用户设置的字体大小
     */
    private void checkFontSize() {
        int fontSize = (int) SharedPreferencesUtil.getParam(this, Constances.FONT_KEY, Constances.MID_FONT);
        if (fontSize == Constances.BIG_FONT) {
            font_tv.setText("大");
        } else if (fontSize == Constances.MID_FONT) {
            font_tv.setText("中");
        } else if (fontSize == Constances.SMALL_FONT) {
            font_tv.setText("小");
        }
    }

//    /**
//     * 检查版本更新
//     */
//    private void checkVersion() {
//        if (isUpdate) {
//            manager = new DownloadManager(MineSettingActivity.this, versionInfo);
//            manager.notifyPermission(true);
//            manager.setAction(new DownloadManager.OnDialogAction() {
//
//                @Override
//                public void onPositiveButtonClick() {
//                    manager.onUpdateAction(MineSettingActivity.this.getSupportFragmentManager());
////                    isUpdate = true;
//                }
//
//                @Override
//                public void OnNegativeButtonClick() {
////                    isUpdate = false;
//
//                }
//
//                @Override
//                public void onUploadFailed() {
//                    toast("更新失败");
//                }
//            });
//            // 检查软件更新
//            if (updateDialog != null && updateDialog.isShowing()) {
//                updateDialog.dismiss();
//            }
////                isForce = false;
//
//            boolean b = manager.checkUpdate(VersionUtil.getVersionCode(MineSettingActivity.this),
//                    versionInfo.getVersionCode(), false, versionInfo.getDescription(), MineSettingActivity.this.getSupportFragmentManager());
//            if (!b) {
////                if (show_type == 1) {
//                toast("已经更新到最新版本啦！");
////                }
//            }
//
//        }
//
//    }


    /**
     * 获取缓存数据大小
     */
    private void initData() {
        try {
            String totalCacheSize = DataCleanManager.getTotalCacheSize(this);
            cache_tv.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查APP的版本号
     */
    public void getVersion() {
        NetUtils.getNetAdapter().getVersion(getOwnerName(), "sctv/appVersion.json", new AbsNetCallBack<FVersionInfo>(FVersionInfo.class) {
            @Override
            public void onSuc(FVersionInfo fVersionInfo) {
                int versionCode = VersionUtil.getVersionCode(MineSettingActivity.this);
                if (fVersionInfo != null && fVersionInfo.getVersionCode() > versionCode) {
                    isUpdate = true;
                    tv_version.setText("有可用新版本");
                    versionInfo = fVersionInfo;
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_TO_LOGIN){
            if(null!=UserManager.getInstance().getUser()) {
                loginOut.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 弹出提示框
     *
     */
    private void showLoginOutDialog() {
//        if (showDiaFragment == null) {
        showDiaFragment = new ShowDiaFragment();
//        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.setType(0);
        showDiaFragment.show(getSupportFragmentManager(), SHOW_TAG);
    }
}
